package com.reservoir.log.handler;

import com.reservoir.core.constant.HttpStatus;
import com.reservoir.core.entity.RestMsg;
import com.reservoir.core.exception.ServiceException;
import com.reservoir.core.exception.auth.NotPermissionException;
import com.reservoir.core.exception.auth.NotRoleException;
import com.reservoir.core.exception.base.BaseException;
import com.reservoir.core.exception.user.UserException;
import com.reservoir.core.exception.user.UserNoExitException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author STARS
 * @创建者 SuiXinTop
 * @创建时间 2021-11-07
 * @描述
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 权限码异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public RestMsg<Object> handleNotPermissionException(NotPermissionException e) {
        log.error("权限码校验失败'{}'", e.getMessage());
        return RestMsg.fail(HttpStatus.FORBIDDEN, "没有访问权限，请联系管理员授权");
    }

    /**
     * 角色权限异常
     */
    @ExceptionHandler(NotRoleException.class)
    public RestMsg<Object> handleNotRoleException(NotRoleException e) {
        log.error("角色权限校验失败'{}'", e.getMessage());
        return RestMsg.fail(HttpStatus.FORBIDDEN, "没有访问权限，请联系管理员授权");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public RestMsg<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e) {
        log.error("不支持请求");
        return RestMsg.fail("请求方式不支持");
    }

    @ExceptionHandler(BaseException.class)
    public RestMsg<Object> handleBaseException(BaseException e) {
        log.error(e.getDefaultMessage());
        return RestMsg.fail(e.getDefaultMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public RestMsg<Object> handleServiceException(ServiceException e) {
        log.error(e.getMessage(), e);
        return RestMsg.fail(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public RestMsg<Object> handleRuntimeException(RuntimeException e) {
        log.error("发生未知异常.", e);
        return RestMsg.fail(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public RestMsg<Object> handleException(Exception e) {
        log.error("发生系统异常.", e);
        return RestMsg.fail(e.getMessage());
    }
}
